#!/usr/bin/env coffee


import ON from '~/lib/broadcast/on.coffee'
import broadcast from '~/lib/broadcast.coffee'
import camelCase from 'lodash/camelCase'

export default new Proxy(
  {}
  get:(self,name)=>
    (init)=>
      broadcast_name = 'S'+camelCase(name)
      store = broadcast[broadcast_name]
      exist = localStorage[name]

      local = if exist then JSON.parse(exist) else init

      config = reactive {...local}

      广播吗 = true

      广播 = (change,del)=>
        if 广播吗
          if (change.size + del.size) > 0
            store(change,del)
            localStorage[name] = JSON.stringify local
        else
          广播吗 = true
        return

      watchEffect =>

        exist = new Set(Object.keys(local))

        del = new Set()
        change = new Map()

        for [k,v] from Object.entries(config)
          exist.delete(k)
          if local[k] != v
            local[k] = v
            change.set k,v

        for i from exist
          delete local[i]
          del.add i

        广播 change,del
        return

      ON[broadcast_name] = (change,del)=>
        广播吗 = false
        for [k,v] from change.entries()
          config[k] = v
        for i from del.values()
          delete config[i]
        return

      config
)
